<script setup>

import {ref, defineProps, onMounted} from 'vue'
import axios from "axios";
import {ElMessage, ElLoading, ElMessageBox} from "element-plus";
import { userStore } from '@/store/index.js'
const userItemStore = userStore();

const props = defineProps({
  orders: {
    type: Array,
    required: true
  },
  urlImage: {
    type: String,
    required: true
  },
  currentStatus: {
    type: String,
    required: true
  }
})

const getOrderButtons = (status) => {
  switch (status) {
    case 1://"待付款"
      return [
        { label: '去支付', type: 'primary', action: payOrder },
        { label: '取消订单', type: 'danger', action: cancelPurchase }
      ];
    case 2://"待发货"
      return [
        { label: '提醒发货', type: 'primary', action: remindDelivery },
        { label: '修改地址', type: 'warning', action: modifyAddress }
      ];
    case 3://"待收货"
      return [
        { label: '确认收货', type: 'primary', action: confirmReceipt }
      ];
    case 4://"待评价"
      return [
        { label: '评价', type: 'success', action: comment }
      ];
    case 5://"退款中"
      return [
        { label: '查询', type: 'success', action: comment }
      ];
    case 6://"售后中"
      return [
        { label: '评价', type: 'success', action: comment }
      ];
    case 7://"已取消"
      return [
        { label: '删除订单', type: 'success', action: deleteOrder}
      ];
    case 8://"已退货"
      return [
        { label: '评价', type: 'success', action: comment }
      ];
    case 9://"已收货"
      return [
        { label: '评价', type: 'success', action: comment }
      ];
    default:
      return [];
  }
};

//支付
const generateUniqueCode = () => {
  const timestamp=Date.now();
  const random = Math.floor(Math.random()*100000);
  const uniqueCode = "xmsc_"+timestamp+random.toString().padStart(5, "0");
  return uniqueCode;
}

const payOrder = (orderId) => {
  ElMessage.success("准备跳转支付界面...");
  setTimeout(()=>{
    location.href=`http://localhost:8080/alipay/pay?id=${orderId}`;
  },2000)

  // const uniqueCode = generateUniqueCode();
  // const orderIdStr = orderId.toString();
  //
  // // 显示加载状态
  // const loadingInstance = ElLoading.service({
  //   fullscreen: true,
  //   text: '正在跳转到支付页面...',
  //   spinner: 'el-icon-loading'
  // });
  //
  // axios.post(`/order/pay/${orderIdStr}/${uniqueCode}`)
  //     .then(resp => {
  //       // 关闭加载状态
  //       loadingInstance.close();
  //
  //       // 安全处理返回的表单
  //       const formContainer = document.createElement('div');
  //       formContainer.innerHTML = resp.data;
  //
  //       // 移除可能存在的旧表单
  //       const oldForms = document.querySelectorAll('form.payment-form');
  //       oldForms.forEach(form => form.remove());
  //
  //       // 添加新表单并设置标识类
  //       const form = formContainer.querySelector('form');
  //       if (form) {
  //         form.classList.add('payment-form');
  //         document.body.appendChild(formContainer);
  //         form.submit();
  //
  //         // 提示用户已开始支付流程
  //         ElMessage({
  //           message: '正在跳转到支付页面，请稍候...',
  //           type: 'info'
  //         });
  //       } else {
  //         throw new Error('支付表单未正确返回');
  //       }
  //     })
  //     .catch(error => {
  //       // 关闭加载状态并显示错误
  //       loadingInstance.close();
  //
  //       console.error('支付请求失败:', error);
  //       ElMessage.error('支付请求失败，请重试');
  //     });
};

const emits=defineEmits('');
const changeOrderStatus = ref(false);
const cancelPurchase = (orderId) => {
  ElMessageBox.confirm(
      `您确定要取消吗？`,
      'warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
  axios.delete(`/order/cancelOrder/${userItemStore.user.id}/${orderId}`).then(resp => {
    ElMessage.success(resp.data);
    emits("changeOrderStatus",props.currentStatus);
  })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })

};

const deleteOrder = (orderId) => {
  ElMessageBox.confirm(
      `您确定要永久删除吗？`,
      'warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    axios.delete(`/order/deleteOrder/${userItemStore.user.id}/${orderId}`).then(resp => {
      ElMessage.success(resp.data);
      emits("changeOrderStatus",props.currentStatus);
    })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })

};


const remindDelivery = (orderId) => {
  console.log("执行提醒发货操作", orderId);
  // 实现提醒逻辑...
};
const confirmReceipt = (orderId) => {
  console.log("实现确认收货的逻辑", orderId);
  // 实现确认收货逻辑...
};
const modifyAddress = () => {
  console.log("执行修改地址操作");
  // 实现修改地址逻辑...
};
const comment = () => {
  console.log("执行评价的操作");
  // 实现评价逻辑...
};

onMounted(()=>{

})

</script>

<template>
  <div>
    <template v-if="orders.length > 0">
      <!-- 显示订单 -->
      <div v-for="(order, index) in orders" :key="index" class="order-middle">
        <el-descriptions>
          <el-descriptions-item label="订单编号">{{ order.orderNum }}</el-descriptions-item>
          <el-descriptions-item label="订单总金额（元）">
            {{ order.totalPrice }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ order.createTime }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ order.receiver }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ order.address }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ order.telephone }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">{{ order.orderStatus }}</el-descriptions-item>
        </el-descriptions>

        <el-table :data="order.orderItem" style="width: 100%" border>
          <el-table-column prop="bookName" label="书籍名称"></el-table-column>
          <el-table-column prop="image" label="书籍图片">
            <template #default="{ row }">
              <el-image style="height: 120px;"
                        :src="$urlImage + row.bookImg"
                        fit="fit">
              </el-image>
            </template>
          </el-table-column>

          <el-table-column prop="buyCount" label="数量" width="100"></el-table-column>
          <el-table-column prop="sumPrice" label="小计" width="100"></el-table-column>
        </el-table>

        <div class="order-footer">
          <!-- 根据订单状态决定显示的按钮 -->
          <el-button
              v-for="button in getOrderButtons(order.status)"
              :key="button.label"
              size="small"
              round
              :type="button.type"
              :icon="button.icon"
              @click="() => button.action(order.id)">
            {{ button.label }}
          </el-button>
        </div>
      </div>
    </template>
    <template v-else>
      <el-empty description="没有查询到订单"></el-empty>
    </template>
  </div>
</template>

<style scoped>
.order-middle {
  border-radius: 5px;
  border: 1px solid #e4e7ed;
  margin-bottom: 20px;
  padding: 10px;
  box-shadow: 0 5px 10px -5px rgba(0, 0, 0, 0.5);
}

.order-footer {
  margin-top: 10px;
  margin-bottom: 5px;
}
</style>